<?php

declare(strict_types=1);

namespace App\Controller\playlet;
use App\Controller\BaseController;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletActor;
use App\Model\PlayletEpisodes;
use App\Model\PlayletSpreadLimit;
use App\Model\PlayletTag;
use App\Model\WeCom;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use App\Common\Response\SystemCode;
use App\Service\playlet\PlayletService;
use Hyperf\DbConnection\Db;
#[AutoController]
class PlayletController  extends BaseController
{

    #[Inject]
    private PlayletService $playletService;
    /**
     * 短剧列表
     */
    public function Index(RequestInterface $request)
    {
        $data = $this->playletService->search($request->query());

        return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功',$data);


    }
    /**
     * 短剧详情
     */
    public function View(int $id,RequestInterface $request)
    {
        if(!empty($id)) {
            $playletInfo = Playlet::query()->select(['id','name','cover','introduction','is_finish','amount','last_episode_number','last_episode_name','pay_start_cid','pay_type','status','likes_number','share_number','hot_number','created_at','updated_at'])->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $playletInfo);
        }
    }
    /**
     * 短剧创建
     */
    public function Create(RequestInterface $request){

        $result = $this->playletService->createOrUpdate($request->post());

        if($result['code'] == SystemCode::SYSTEM_SUCCESS){
            return $this->response(SystemCode::SYSTEM_SUCCESS, '创建成功');
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR, $result['message']);

        }
    }
    /**
     * 短剧删除
     */
    public function Delete(int $id,RequestInterface $request)
    {
        if(!empty($id)) {
            $playletInfo = Playlet::query()->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }

            //2024-01-02 抖音过审不给删除和修改
            if($playletInfo->drama_status == 3){
                return $this->response(SystemCode::SYSTEM_ERROR, '审核通过不允许删除');
            }

            $playletInfo->deleted_at = date('Y-m-d H:i:s');
            $playletInfo->save();
            return $this->response(SystemCode::SYSTEM_SUCCESS, '操作成功');
        }
    }
    /**
     * 短剧更新
     */
    public function Update(int $id,RequestInterface $request){

        if(empty($id)){
            return $this->response(SystemCode::SYSTEM_ERROR, '错误请求');
        }else{

            $playletInfo = Playlet::query()->select(['id','name','alias_name','producer','registration_number','thumbnail','drama_status','registration_number_url','cover','introduction','is_finish','amount','last_episode_number','last_episode_name','pay_start_cid','pay_type','status','playlet_type'])->where('id', $id)->first();


            if(empty($playletInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            if($request->getMethod() == 'GET'){

                //查询短剧标签
                $tag_id = PlayletTag::query()->where(['playlet_id' => $playletInfo->id])->pluck('tag_id');
                $playletInfo->tag_ids = $tag_id;
                $playletInfo->actorList = [['actor_id' => '','role_name' => ''],['actor_id' => '','role_name' => '']];
                //查询短剧演员
                $actorList = PlayletActor::query()->where(['playlet_id' => $playletInfo->id])
                                ->leftJoin('actor','playlet_actor.actor_id','=','actor.id')
                                ->select([Db::Raw('actor.id as actor_id'),'role_name'])->get()->toArray();
                if(!empty($actorList)){

                    if(count($actorList) == 1){
                        $actorList[] =['actor_id' => '','role_name' => ''];
                    }
                    $playletInfo->actorList = $actorList;
                }

                return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$playletInfo);

            }else{
                //2024-01-02 抖音过审不给删除和修改
//                if($playletInfo->drama_status == 3){
//                    return $this->response(SystemCode::SYSTEM_ERROR, '审核通过不允许修改');
//                }


                $result = $this->playletService->createOrUpdate($request->post(),true,$playletInfo);

                if($result['code'] == SystemCode::SYSTEM_SUCCESS){
                    return $this->response(SystemCode::SYSTEM_SUCCESS, '修改成功');
                }else{
                    return $this->response(SystemCode::SYSTEM_ERROR, $result['message']);

                }
            }
        }
    }

    public function Episodes(int $id){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select('id')->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            $playletEpisodesInfo = PlayletEpisodes::query()->select(['playlet_number as value','playlet_number_name as label'])->where(['playlet_id' => $id])->get();
            return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $playletEpisodesInfo);
        }

    }

    public function EpisodesList(int $id){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select('id')->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            $playletEpisodesInfo = PlayletEpisodes::query()->select(['playlet_number','playlet_number_name','original_play_url','play_url','wx_original_url','cover'])->where(['playlet_id' => $id])->orderBy('playlet_number','asc')->get();
            return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功', $playletEpisodesInfo);
        }

    }

    public function batchUpload(int $id,RequestInterface $request){

        $playletInfo = Playlet::query()->select(['id','cover'])->where('id', $id)->first();
        if (empty($playletInfo)) {
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
        }
        $result = $this->playletService->batchUpload($request->post(),$id,$playletInfo->cover);
        if($result['code'] == SystemCode::SYSTEM_SUCCESS){
            return $this->response(SystemCode::SYSTEM_SUCCESS, '上传成功');
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR, $result['message']);
        }
    }
    /**
     * 限制推广链接的集数
     */
    public function limitNumber(int $id,RequestInterface $request){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select(['id'])->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            $limintData = PlayletSpreadLimit::query()->where('playlet_id',$id)->first();

            if($request->getMethod() == 'GET'){

                if(empty($limintData)){
                    $limintData = new PlayletSpreadLimit();
                    $limintData->playlet_id = $id;
                    $limintData->pay_episodes_number = 0;
                }
                return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$limintData);
            }else{
                $postData = $request->post();

                if(empty($postData['pay_episodes_number'])){
                    return $this->response(SystemCode::SYSTEM_ERROR, '请选择集数');
                }

                if(empty($limintData)){
                   $is_success =  PlayletSpreadLimit::create(['playlet_id' => $id,'pay_episodes_number' => $postData['pay_episodes_number']]);
                }else{
                    $limintData->pay_episodes_number = $postData['pay_episodes_number'];
                    $is_success = $limintData->save();

                }
                if($is_success){
                    return $this->response(SystemCode::SYSTEM_SUCCESS, '编辑成功');
                }else{
                    return $this->response(SystemCode::SYSTEM_ERROR, '编辑失败');
                }
            }
        }
    }

    /**
     * 添加授权书到期时间
     */
    public function registrationTime(int $id,RequestInterface $request){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select(['id','registration_at'])->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            if($request->getMethod() == 'GET'){

                return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$playletInfo);
            }else{
                $postData = $request->post();

                if(empty($postData['registration_at'])){
                    return $this->response(SystemCode::SYSTEM_ERROR, '请选择时间');
                }

                $playletInfo->registration_at = $postData['registration_at'];

                $is_success = $playletInfo->save();

                if($is_success){
                    return $this->response(SystemCode::SYSTEM_SUCCESS, '编辑成功');
                }else{
                    return $this->response(SystemCode::SYSTEM_ERROR, '编辑失败');
                }
            }
        }
    }

    public function clickOnline(int $id){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select(['id'])->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            //查询所有短剧剧集是否有status
            $playletEpisodesData = PlayletEpisodes::query()->where(['playlet_id' => $id,'status' => 0])->get();

            if($playletEpisodesData->isNotEmpty()){

                //2024-01-26 剧集上线 加事务
                Db::beginTransaction();
                try {

                    Db::table('playlet_episodes')->where(['playlet_id' => $id])->update(['status' => 1]);
//                    foreach ($playletEpisodesData as $playletEpisodesDatum){
//                        $playletEpisodesDatum->status = 1;
//                        $playletEpisodesDatum->save();
//                    }
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollBack();
                    return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
                }
                return $this->response(SystemCode::SYSTEM_SUCCESS, '上线成功');
            }else{
                return $this->response(SystemCode::SYSTEM_ERROR, '所有集数都已上线');
            }
        }
    }
    public function clickOffline(int $id){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select(['id'])->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            //查询所有短剧剧集是否有status
            $playletEpisodesData = PlayletEpisodes::query()->where(['playlet_id' => $id,'status' => 1])->get();

            if($playletEpisodesData->isNotEmpty()){

                //2024-03-22 剧集下线 加事务
                Db::beginTransaction();
                try {

                    Db::table('playlet_episodes')->where(['playlet_id' => $id])->update(['status' => 0]);
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollBack();
                    return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
                }
                return $this->response(SystemCode::SYSTEM_SUCCESS, '下线成功');
            }else{
                return $this->response(SystemCode::SYSTEM_ERROR, '所有集数都已下线');
            }
        }
    }

    /**
     * 合并短剧
     */
    public function mergePlaylet(RequestInterface $request){

        $result = $this->playletService->mergePlaylet($request->post());

        if($result['code'] == SystemCode::SYSTEM_SUCCESS){
            return $this->response(SystemCode::SYSTEM_SUCCESS, '创建成功');
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR, $result['message']);

        }
    }

    /**
     * 短剧绑定企业微信
     */

    public function weComBind(int $id,RequestInterface $request){

        if(!empty($id)) {
            $playletInfo = Playlet::query()->select(['id','we_com_id'])->where('id', $id)->first();
            if (empty($playletInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
            }
            if($request->getMethod() == 'GET'){

                return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$playletInfo);
            }else{
                $postData = $request->post();

                if(empty($postData['we_com_id'])){
                    return $this->response(SystemCode::SYSTEM_ERROR, '请选择企业微信');
                }
                $we_com_id = $postData['we_com_id'];
                $weComInfo = WeCom::query()->where('id',$we_com_id)->first();
                if(empty($weComInfo)){
                    return $this->response(SystemCode::SYSTEM_ERROR, '企业微信不存在');
                }
                $playletInfo->we_com_id = $weComInfo->id;
                $playletInfo->we_com_cover = $weComInfo->cover;
                if($playletInfo->save()){
                    return $this->response(SystemCode::SYSTEM_SUCCESS, '绑定成功');
                }else{
                    return $this->response(SystemCode::SYSTEM_ERROR, '绑定失败');
                }
            }
        }
    }
}